package com.lagou.rocketmq.service.impl;

import com.lagou.rocketmq.entity.Order;
import com.lagou.rocketmq.entity.ProductStock;
import com.lagou.rocketmq.mapper.OrderMapper;
import com.lagou.rocketmq.mapper.ProductStockMapper;
import com.lagou.rocketmq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    private static boolean isSellout = false;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public boolean placeOrder(Integer productId, Long userId) {

        if(isSellout) {
            log.info("检查销售状态,商品已售完,商品id:" + productId);
            return false;
        }

        Integer productNum = (Integer)redisTemplate.opsForValue().get(productId);
        if(productNum <= 0) {
            isSellout = true;
            log.info("检查redis库存,商品已售完,商品id:" + productId);
            return false;
        }

        Order order = new Order();
        order.setProductId(productId);
        order.setUserId(userId);

        rocketMQTemplate.asyncSend("place_order", order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                Integer productNum = (Integer) redisTemplate.opsForValue().get(productId);
                redisTemplate.opsForValue().set(productId, productNum - 1);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });

        return true;
    }

    public Long addOrder(Integer productId, Long userId) {
        Order order = new Order();
        order.setProductId(productId);
        order.setUserId(userId);
        order.setStatus(0);//待支付
        order.setBuyNum(1);
        order.setProductName("华为手机");
        order.setProductPrice(5000);

        orderMapper.add(order);

        return order.getId();
    }

    public void cancelOrder(Long orderId) {
        Long result = orderMapper.updateStatusById(-1, orderId, 0);
        if(result <= 0) {
            log.info("取消订单失败");
        }
    }

    public Integer getStatus(Long orderId) {
        return orderMapper.findStatusById(orderId);
    }
}
